/**
 * 
 */
package info.niwota.fwrite.imglist;

import info.niwota.fwrite.Debug;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class ImageUtil {
	private static final String TAG = "ImageUtil";

	public static final String IMAGE_SORT_BY_DATE_DESC = dateSortOrder(false);
	public static final int MAX_COUNT = 32;

	// The list is first sorted by date, then by id. The order can be ascending
	// or descending
	// The date is obtained from the "datetaken" column. But if it is null,
	// the "date_modified" column is used instead.
	private static String dateSortOrder(boolean asc) {
		String ascending = (asc) ? " ASC" : " DESC";

		// Use DATE_TAKEN if it's non-null, otherwise use DATE_MODIFIED.
		// DATE_TAKEN is in milliseconds, but DATE_MODIFIED is in seconds.
		String dateExpr = "case ifnull(datetaken,0)"
				+ " when 0 then date_modified*1000" + " else datetaken"
				+ " end";

		// Add id to the end so that we don't ever get random sorting
		// which could happen, I suppose, if the date values are the same.
		return dateExpr + ascending + ", _id" + ascending;
	}

	public static final String[] IMAGE_PROJECTION = new String[] { Media._ID,
			Media.DATA, Media.DATE_TAKEN, Media.MINI_THUMB_MAGIC,
			Media.ORIENTATION, Media.TITLE, Media.MIME_TYPE,
			Media.DATE_MODIFIED };

	public static boolean isMediaScannerScanning(ContentResolver cr) {
		boolean result = false;
		Cursor cursor = query(cr, MediaStore.getMediaScannerUri(),
				new String[] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null,
				null);
		if (cursor != null) {
			if (cursor.getCount() == 1) {
				cursor.moveToFirst();
				result = "external".equals(cursor.getString(0));
			}
			cursor.close();
		}

		return result;
	}

//	public static long getImageFileSize(IImage image) {
//		InputStream data = image.fullSizeImageData();
//		if (data == null) {
//			return -1;
//		}
//		try {
//			return data.available();
//		} catch (java.io.IOException ex) {
//			return -1;
//		} finally {
//			closeSilently(data);
//		}
//	}

//	private static void closeSilently(InputStream c) {
//		if (c == null) {
//			return;
//		}
//		try {
//			c.close();
//		} catch (Throwable t) {
//			// do nothing
//		}
//	}

	public static Cursor query(ContentResolver cr, Uri uri, String[] proj,
			String sel, String[] args, String orderby) {
		Cursor c = cr.query(uri, proj, sel, args, orderby);
		return c;
	}

	public static Cursor queryRecent(ContentResolver cr, Uri uri) {
		//final Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		final String by = IMAGE_SORT_BY_DATE_DESC;
		Cursor c = cr.query(uri, IMAGE_PROJECTION, null, null, by);
		if (Debug.DEBUG) {
			Log.d(TAG, "init " + uri + " by: " + by + " cursor: " + c);
		}
		return c;
	}

//	public static Uri queryFirst(ContentResolver cr, Uri uri) {
//		try {
//			Cursor c = queryRecent(cr, uri);
//			if (c == null) {
//				return null;
//			}
//			if (!c.moveToFirst()) {
//				return null;
//			}
//			if (Debug.DEBUG) {
//				Log.d(TAG, "loadImageList " + c + " count: " + c.getCount());
//			}
//			int idIdx = c.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
//			long id = c.getLong(idIdx);
//			return contentUri(uri, id);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

//	public static Uri contentUri(Uri base, long id) {
//		//MediaStore.Images.Media.EXTERNAL_CONTENT_URI
//		Uri uri = ContentUris.withAppendedId(base, id);
//		if (Debug.DEBUG) {
//			Log.d(TAG, "contentUri: " + id + " uri: " + uri);
//		}
//		return uri;
//	}
}
